define(function (require, exports, module){
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        user_models = require('js/apps/console/models'),
        utils = require('js/utils/tools'),
        tz = require('js/utils/tz'),
        cookie = require('js/utils/cookie'),
        app = Backbone.history;
    require('datetimepicker');
    require('multiselect');
    require('magnific');

    var AccountBlackCustomerView = Backbone.View.extend({
        tagName: "div",
        events: {
            'click #search': 'doSearch'
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.AccountBlackCollection();
            this.user_collection = new user_models.UserCollection();
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        _getSearchOpthin: function () {
            var options = {};
            var searched = utils.getAllInput('#sidebar_right');
            searched.account_id = $('#searchUid').val();
            searched.target_type = parseInt($('#searchType').val());
            searched.withdraw_target_type = parseInt($('#searchWithdrawType').val());
            searched.bind_type = $('#searchBindType').val();
            searched.account_ip = $('#searchIP').val();
            searched.account_aid = $('#searchAid').val();
            if(searched.account_ip){
                options.account_ip = searched.account_ip;
            }
            if(searched.account_aid){
                options.account_aid = searched.account_aid;
            }
            if (searched.account_id) {
              options.account_id = searched.account_id;
            }
            if (searched['target_type'] != -1) {
                options['status'] = searched['target_type'];
            }
            if (searched['withdraw_target_type'] != -1) {
                options['withdraw_status'] = searched['withdraw_target_type'];
            }
            if (searched['bind_type'] != -1) {
                options['fin_account_type'] = searched['bind_type'];
            }
            utils.saveSearched('op/account/black', searched);
            return options;
        },
        doSearch: function () {
            var account_id = $('#searchUid').val();
            if(null == account_id || '' == account_id){
                notify.notifyResp("请输入用户ID");
            }else{
                var options = this._getSearchOpthin();
                options.$page = 1;
                options.$size = 20;
                options._ = new Date().getTime();
                app.navigate(utils.composeQueryString('#op/account_black_customer/', options), {
                    trigger: true
                });
            }

        },
        renderWithData: function () {
            var user_dict = {};
            _.each(this.user_collection.toJSON(), function (k) {
                user_dict[k.id] = k.nickname;
            });
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/account/black')
            }));
            var that = this;
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/account_black_customer/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            utils.getPaginator(that.options, this.collection.total, '#op/account_black_customer/');
            $('.modify-item').magnificPopup({
                items: {
                    src: '#editAccount',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {
                        $('#riskInfo').html('');
                        var data_id = $(this.st.el).closest('tr').data('id'),
                            choosen = that.collection.get(data_id);
                        console.log(choosen);
                        var user_attributes = choosen.attributes;
                        var user_id = choosen.get('id');
                        if(user_attributes.status == 1024){
                            $('#blackUser').hide();
                            $('#unblackUser').show();
                        } else {
                            $('#unblackUser').hide();
                            $('#blackUser').show();
                        }
                        var black_modification_display_ref = {
                            'withdraw_black': {
                                'show': 'unblackUserWithdraw',
                                'hide': 'blackUserWithdraw'
                            },
                            'withdraw_test': {
                                'show': 'unblackTestWithdraw',
                                'hide': 'blackTestWithdraw'
                            },
                            'withdraw_sales': {
                                'show': 'unblackUserSales',
                                'hide': 'blackUserSales'
                            },
                            'withdraw_op':{
                                'show': 'unblackOp',
                                'hide': 'blackOp'
                            }
                        };
                        _.each(black_modification_display_ref, function (value, key){
                            if(user_attributes[key]){
                                $('#' + value['show']).show();
                                $('#' + value['hide']).hide();
                            }else{
                                $('#' + value['show']).hide();
                                $('#' + value['hide']).show();
                            }
                        });
                        var unbind_modification_display_ref = {
                            'phone': 'unbindUserPhone',
                            'wechat': 'unbindWechat',
                            'alipay': 'unbindAlipay',
                            'bank_card': 'unbindBankcard',
                        };
                        _.each(unbind_modification_display_ref, function (value, key){
                            if(user_attributes[key]){
                                $('#' + value).show();
                            }else{
                                $('#' + value).hide();
                            }
                        });
                        var account_mod_reference = {
                            'account_banned': {
                                'name': '封号历史记录',
                                'content_id': 'banned_history'
                            },
                            'test_uid': {
                                'name': '测试用户历史记录',
                                'content_id': 'test_history'
                            },
                            'black_uid': {
                                'name': '提现黑名单历史记录',
                                'content_id': 'black_history'
                            },
                            'black_phone':{
                                'name': '解绑手机号历史记录',
                                'content_id': 'black_phone'
                            },
                            'black_bank': {
                                'name': '解绑银行卡历史记录',
                                'content_id': 'black_bank_history'
                            },
                            'black_alipayno':{
                                'name': '解绑支付宝历史记录',
                                'content_id': 'black_alipayno_history'
                            },
                            'black_wechat':{
                                'name': '解绑微信历史记录',
                                'content_id': 'black_wechat_history'
                            }
                        };
                        $.ajax({
                            url: '/admin/withdraw/user_black_modification/get/',
                            type: 'GET',
                            headers: {
                                'X-AUTH-USER': cookie.getCookie('bigbang_user_id'),
                                'X-AUTH-TOKEN': cookie.getCookie('bigbang_user_token'),
                                'content-type': 'application/json'
                            },
                            data: {'user_id': user_id}
                        }).done(function (resp) {
                            $('#AccountForm').empty();
                            var has_mod = false;
                            if(resp.data) {
                                _.each(account_mod_reference, function (value, key) {
                                    if(resp.data[key] && resp.data[key].length > 0) {
                                        has_mod = true;
                                        var base_content = '<div class="form-group">' +
                                        '<label for="detailHistory" class="col-md-3 control-label">' +
                                        account_mod_reference[key]['name'] +
                                        '：</label><div class="col-md-9">' +
                                        '<p class="form-control-static text-muted" id="' +
                                        account_mod_reference[key]['content_id'] + '"></p></div>';
                                        $('#AccountForm').append(base_content);
                                        for (var mod_obj in resp.data[key]) {
                                            var action = '洗白';
                                            if(resp.data[key][mod_obj].status == 1) action = '拉黑';
                                            $('#' + account_mod_reference[key]['content_id']).append(
                                                action + '操作时间: ' + resp.data[key][mod_obj].created_at + '<br>' +
                                                '操作人: ' + user_dict[resp.data[key][mod_obj].admin_id] + '<br>' +
                                                '原因: ' + (resp.data[key][mod_obj].reason || '-') + '<br><br>'
                                            );
                                        }
                                    }
                                });
                            }
                            if(!has_mod){
                                $('#AccountForm').append('<p>无操作记录</p>');
                            }
                        }).fail(function (resp) {
                            console.log(JSON.stringify(resp));
                        });
                        $('.unbind_financial').off('click').click(function () {
                            var reason = window.prompt("请填写解绑原因");
                            if (!reason) {
                                alert("解绑原因不能为空");
                            } else {
                                var account_type = $(this).data("account_type");
                                var post_data = {
                                    'user_id': user_id,
                                    'account_type': account_type,
                                    'reason': reason
                                };
                                $.post('/admin/user/financial_account/unbind/', post_data).done(function (resp) {
                                    notify.success('操作成功');
                                    location.reload();
                                }).fail(function (data) {
                                    notify.notifyResp(data);
                                });
                            }
                        });
                        $('.added_withdraw_black,.removed_withdraw_black').off('click').click(function () {
                            var type = $(this).data("type");
                            var status, prompt_msg, alert_msg;
                            if($(this).hasClass('removed_withdraw_black')){
                                status = 2;
                                prompt_msg = '请填写洗白原因';
                                alert_msg = '洗白原因不能为空';
                            }else{
                                status = 1;
                                prompt_msg = '请填写拉黑原因';
                                alert_msg = '拉黑原因不能为空';
                            }
                            var reason = window.prompt(prompt_msg);
                            if (!reason) {
                                alert(alert_msg);
                            }
                            else{
                                var post_data = {
                                    'type_account': user_id,
                                    'type': type,
                                    'reason': reason,
                                    'status': status
                                };
                                $.post('/admin/withdraw/black/set/', JSON.stringify(post_data)).done(function (resp) {
                                    notify.success('操作成功');
                                    location.reload();
                                }).fail(function (data) {
                                    notify.notifyResp(data);
                                });
                            }
                        });

                        $('#unbindUserPhone').off('click').click(function () {
                            var reason = window.prompt("请填写解绑原因");
                            if (!reason) {
                                alert("解绑原因不能为空");
                            } else {
                                var post_data = {
                                    'id': user_id,
                                    'reason': reason
                                };
                                $.post('/admin/user/reset_user_phone/', post_data).done(function (resp) {
                                    notify.success('操作成功');
                                    location.reload();
                                }).fail(function (data) {
                                    notify.notifyResp(data);
                                });
                            }
                        });
                        $('.banned_account, .unbanned_account').off('click').click(function () {
                            var status, prompt_msg, alert_msg;
                            if($(this).hasClass('unbanned_account')){
                                status = 'UNBLACK';
                                prompt_msg = '请填写解封原因';
                                alert_msg = '洗白原因不能为空';
                            }else{
                                status = 'BLACK';
                                prompt_msg = '请填写封号原因';
                                alert_msg = '拉黑原因不能为空';
                            }
                            var reason = window.prompt(prompt_msg);
                            if (!reason) {
                                alert(alert_msg);
                            }
                            else{
                                var post_data = {'account_id': user_id,'status': status,"reason":reason};
                                $.post('/admin/account_black/set_black_account/', JSON.stringify(post_data)).done(function (resp) {
                                    notify.success('操作成功');
                                    location.reload();
                                }).fail(function (data) {
                                    notify.notifyResp(data);
                                });
                            }
                        });

                        $('#submitClose').off('click').click(function() {
                            $.magnificPopup.close();
                        });
                    },
                }
            });

            return this;
        },

        load:function(){
            var that = this;
            this.user_collection.fetch({
                reset: true,
                data: {'disable_paginate': 1},
                success: function () {
                    that.collection.fetch({
                        reset: true,
                        data: that.options,
                        error: function (c, r, o) {
                            notify.notifyResp(r);
                        }
                    });
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                }
            });
        },

    });

    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/AccountBlackCustomer.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            this.options.$size = 20;
            if(null == this.options.account_id){
                this.options.account_id = -1;
            }
            this.options.$orderby = "-id";
            var view = new AccountBlackCustomerView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});

var account_black = {
    delBlack: function(user_id){
        console.log(account_black.getCookie('bigbang_user_id'));
        console.log(account_black.getCookie('bigbang_user_token'));
        var data = {'account_id': user_id,'status': 'UNBLACK',};
        var json_data = JSON.stringify(data);
        $.ajax({
            url: '/admin/account_black/set_black_account/',
            type: 'POST',
            headers: {
                'X-AUTH-USER': account_black.getCookie('bigbang_user_id'),
                'X-AUTH-TOKEN': account_black.getCookie('bigbang_user_token')
            },
            data: json_data
        }).done(function (resp) {
            alert('移除黑名单成功！');
            location.reload();
            console.log(JSON.stringify(resp));
        }).fail(function (resp) {
            alert('移除黑名单失败！');
            console.log(JSON.stringify(resp));
        });
    },

    addBlack: function (user_id) {
        $('#account_id').text(user_id);
        $("#AccountBlackDialog").show();
     },

    closeAccountBlackDialog: function () {
        $("#AccountBlackDialog").hide();
    },

    accountBlack: function () {
        user_id = $('#account_id').text();
        reason = $('#black-content').val();
        console.log(account_black.getCookie('bigbang_user_id'));
        console.log(account_black.getCookie('bigbang_user_token'));
        var data = {'account_id': user_id,'status': 'BLACK',"reason":reason};
        var json_data = JSON.stringify(data);
        $.ajax({
            url: '/admin/account_black/set_black_account/',
            type: 'POST',
            headers: {
                'X-AUTH-USER': account_black.getCookie('bigbang_user_id'),
                'X-AUTH-TOKEN': account_black.getCookie('bigbang_user_token')
            },
            data: json_data
        }).done(function (resp) {
            alert('加入黑名单成功！');
            location.reload();
            account_black.closeAccountBlackDialog();
            console.log(JSON.stringify(resp));
        }).fail(function (resp) {
            alert('加入黑名单失败！');
            console.log(JSON.stringify(resp));
        });
    },

    getCookie : function (name) {
        var cookieName = name + "=";
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var c = cookies[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(cookieName) != -1) return c.substring(cookieName.length, c.length);
        }
        return "";
    },
}


